# -*-coding:utf-8-*-

import time, cookielib, threading, random
import logConfig as log
from protocol import *
from threadCenter import *
from interfaceFunc import *

# 测试平台：tcpapp服务
# 调用方式：多线程，分批次
# 涉及接口：TCP接入接口、TCP心跳接口、进入语音频道接口
# TCP进入语音频道# step1：创建多线程 step2：每个线程进行登录请求，登录成功后进入下一步 step3：发起获取所有群组誉城苑信息的请求 step4：发起TCP接入的请求 step5建立TCP心跳线程 step6：发起进入群组的请求
def PT_getOnlineNumMax(cpu, name, password, startNum, endNum, groupNum):
    log.info("Start execute the function PT_getOnlineNumMax")
    cpu["data"]._const["PressureTest"]["loginNum"] = 0
    cpu["data"]._const["PressureTest"]["groupQueryNum"] = 0
    cpu["data"]._const["PressureTest"]["tcpInNum"] = 0
    cpu["data"]._const["PressureTest"]["heartbeatNum"] = 0
    cpu["data"]._const["PressureTest"]["inChannelNum"] = 0
    cpu["data"].ArrayRange = [startNum, endNum+1]

    lock = threading.Lock()

    for i in range(startNum, endNum+1):
        if i == startNum:
            thread_PT_getOnlineNumMax(cpu, name, password, i, groupNum, lock, True)
        else:
            thread_PT_getOnlineNumMax(cpu, name, password, i, groupNum, lock, False)
    time.sleep(10)

    if lock.acquire():
        log.info("The login success num is:"+str(cpu["data"]._const["PressureTest"]["loginNum"]))
        log.info("The groupQuery success num is:"+str(cpu["data"]._const["PressureTest"]["groupQueryNum"]))
        log.info("The tcpInNum success num is:"+str(cpu["data"]._const["PressureTest"]["tcpInNum"]))
        log.info("The heartbeatNum num is:"+str(cpu["data"]._const["PressureTest"]["heartbeatNum"]))
        log.info("The inChannelNum num is:"+str(cpu["data"]._const["PressureTest"]["inChannelNum"]))
        lock.release()

# 线程说明：创建压力测试线程的函数
# 测试接口：创建用户、删除用户、HTTP登录、获取所有群组与成员信息、进入群组通道
def thread_PT_getOnlineNumMax(cpu, name, password, index, groupNum, lock, isRtpSend):
    try:
        thread_PT_getOnlineNumMax = threading.Thread(target=intercom_getOnlineNumMax, args=(cpu, name, password, index, groupNum, lock, isRtpSend))
        thread_PT_getOnlineNumMax.start()
    except Exception, e:
        log.error("Error is occur in create thread of getOnlineNumMax" + str(e))

def intercom_getOnlineNumMax(cpu, name, password, index, groupNum, lock, isRtpSend):
    username = name+str(index)
    userType = 2
    
    uid = 0
    defaultGroupId = 0
    cmpid = 0
    key = ""
    groupListArray = []
    nextflag = 0
    
    startTime_all = time.time()
    response = pressure_fnHttpPost_app(cpu["data"]._const["WS"]["CONFIG"]["HOST"], cpu["data"]._const["HTTP"]["PORT"], '/fn/app/login.do', getLoginMsg(username, password, userType))
    if response["status"] == 'success' and response["content"]["status"] == 1000:
        if lock.acquire():
            cpu["data"]._const["PressureTest"]["loginNum"] += 1
            lock.release()
        uid = response["content"]["body"]["userid"]
        cmpid = response["content"]["body"]["companyId"]
        defaultGroupId = response["content"]["body"]["defaultGroupId"]
        key = response["content"]["body"]["userToken"]
        nextflag = 1

    if nextflag == 1:
        if defaultGroupId == 0:
            response = pressure_fnHttpPost_app(cpu["data"]._const["WS"]["CONFIG"]["HOST"], cpu["data"]._const["HTTP"]["PORT"], '/fn/app/groupQuery.do', getGroupQueryMsg(uid, cmpid, userType, '', key))
            if response["status"] == 'success' and response["content"]["status"] == 1000:
                groupList = json.loads(response["content"]["body"])
                for group in groupList:
                    groupListArray.append(str(group["groupId"]))
                defaultGroupId = groupListArray[groupNum]

        websocket = pressure_webSocket(cpu, cpu["data"]._const["WS"]["CONFIG"]["HOST"], cpu["data"]._const["WS"]["CONFIG"]["PORT"], cpu["data"]._const["WS"]["CONFIG"]["PATH"], cmpid, uid, password, key, index, isRtpSend)
        times = 0
        while True:
            if(websocket.statCon == True):
                websocket.startTime_tcpIn = time.time()
                websocket.wsTcpSend(assemblyTCPData(1, 1, 1, getAccessMsg(cmpid, uid, md5(password), userType, FN_KEY)))
                break
            else:
                if times > cpu["data"]._const["PressureTest"]["maxTimeout"]:
                    return -1
                else:
                    times+=1
                time.sleep(0.001)
        times = 0
        while True:
            if(websocket.statTcpIn == True):
                websocket.startTime_heart = time.time()
                if lock.acquire():
                    cpu["data"]._const["PressureTest"]["tcpInNum"] += 1
                    lock.release()
                
                websocket.wsTcpSend(assemblyTCPData(2, 1, 0, getHeartBeatMsg(cmpid, uid, websocket.token)))
                break
            else:
                if times > cpu["data"]._const["PressureTest"]["maxTimeout"]:
                    return -1
                else:
                    times+=1
                time.sleep(0.001)
        thread_heartbeat = threading.Thread(target=heartbeat, args=(websocket, cmpid, uid, websocket.token))
        thread_heartbeat.start()

        times = 0
        while True:
            if(websocket.statHeart == True):
                websocket.startTIme_inChannel = time.time()
                if lock.acquire():
                    cpu["data"]._const["PressureTest"]["heartbeatNum"] += 1
                    lock.release()
                
                websocket.wsTcpSend(assemblyTCPData(3, 1, 1, getInVoiceChannelMsg(cmpid, uid, defaultGroupId, cpu["data"]._const["CHANNEL_TYPE"]["intercom"])))
                break
            else:
                if times > cpu["data"]._const["PressureTest"]["maxTimeout"]:
                    return -1
                else:
                    times+=1
                time.sleep(0.001)

        times = 0
        while True:
            if(websocket.statInChannel == True):
                if lock.acquire():
                    cpu["data"]._const["PressureTest"]["inChannelNum"] += 1
                    lock.release()    
                websocket.endTime_inChannel = time.time()
                endTime_all = time.time()
                useTime_all = endTime_all - startTime_all
                break
            else:
                if times > cpu["data"]._const["PressureTest"]["maxTimeout"]:
                    return -1
                else:
                    times+=1
                time.sleep(0.001)

        useTime_creatWS = websocket.endTime_init - websocket.startTime_init
        useTime_tcpIn = websocket.endTime_tcpIn - websocket.startTime_tcpIn
        useTime_heart = websocket.endTime_heart - websocket.startTime_heart
        useTime_inChannel = websocket.endTime_inChannel - websocket.startTIme_inChannel

        if cpu["data"]._const["PressureTest"]["timeMin_tcpIn"] == 0:
            cpu["data"]._const["PressureTest"]["timeMin_tcpIn"] = useTime_tcpIn
        elif useTime_tcpIn < cpu["data"]._const["PressureTest"]["timeMin_tcpIn"]:
            cpu["data"]._const["PressureTest"]["timeMin_tcpIn"] = useTime_tcpIn
        if useTime_tcpIn > cpu["data"]._const["PressureTest"]["timeMax_tcpIn"]:
            cpu["data"]._const["PressureTest"]["timeMax_tcpIn"] = useTime_tcpIn

        if cpu["data"]._const["PressureTest"]["timeMin_heart"] == 0:
            cpu["data"]._const["PressureTest"]["timeMin_heart"] =useTime_heart
        elif useTime_heart < cpu["data"]._const["PressureTest"]["timeMin_heart"]:
            cpu["data"]._const["PressureTest"]["timeMin_heart"] = useTime_heart
        if useTime_heart > cpu["data"]._const["PressureTest"]["timeMax_heart"]:
            cpu["data"]._const["PressureTest"]["timeMax_heart"] = useTime_heart

        if cpu["data"]._const["PressureTest"]["timeMin_inChannel"] == 0:
            cpu["data"]._const["PressureTest"]["timeMin_inChannel"] = useTime_inChannel
        elif useTime_inChannel < cpu["data"]._const["PressureTest"]["timeMin_inChannel"]:
            cpu["data"]._const["PressureTest"]["timeMin_inChannel"] = useTime_inChannel
        if useTime_inChannel > cpu["data"]._const["PressureTest"]["timeMax_inChannel"]:
            cpu["data"]._const["PressureTest"]["timeMax_inChannel"] = useTime_inChannel

        if lock.acquire():
            log.info("The login success num is:"+str(cpu["data"]._const["PressureTest"]["loginNum"]))
            log.info("The groupQuery success num is:"+str(cpu["data"]._const["PressureTest"]["groupQueryNum"]))
            log.info("The tcpInNum success num is:"+str(cpu["data"]._const["PressureTest"]["tcpInNum"]))
            log.info("The heartbeatNum num is:"+str(cpu["data"]._const["PressureTest"]["heartbeatNum"]))
            log.info("The inChannelNum num is:"+str(cpu["data"]._const["PressureTest"]["inChannelNum"]))
            lock.release()
